#!/usr/bin/env node


const fs = require('fs'),
      file = process.argv[3],
      join = require('path').join;
      
//输出文件夹下文件信息
if(process.argv[2] === '-list'){
  try{

    let list = fs.readdirSync('sysFile');
    let arr = [];
    for(let i=0;i<list.length;i++){
      const stats = fs.statSync(`${__dirname}/sysFile/${list[i]}`);
      arr[i] = new Object();
      arr[i].filename = list[i];
      arr[i].size = stats.size;
      arr[i].createTime = stats.birthtimeMs;
    }
   
    for(let i=0; i<arr.length; i++){
      for(let j=0;j<i;j++){
        let a = [];
        if(arr[i].createTime < arr[j].createTime){
          a = arr[i];
          arr[i] = arr[j];
          arr[j] = a;
        }
      }
    }

    for(let i=0; i<arr.length;i++){
      let d = new Date(arr[i].createTime)
      let time = d.getFullYear()+'-'+(d.getMonth()+1)+'-'+d.getDate()+' '+d.getHours()+':'+d.getMinutes();
      arr[i].createTime = time
    }

    console.log(JSON.stringify(arr,',',2));

  }catch(e){
    console.error(e.message);
    process.exit(1);
  }
}

//打印文件内容
if(process.argv[2] === '-show'){
  let src = `./sysFile/${file}`;

  if(!fs.existsSync(src)){
    console.error('文件不存在');
    process.eixt(2);
  }

  
  const content = fs.readFileSync(src,'utf8');
  console.log(content);
  
}



//删除文件或文件夹
if(process.argv[2] === '-del'){
  let src = `./sysFile/${file}`;

  if(process.argv.length === 3){
    console.error('请指定要删除的文件或文件夹');
    process.exit(3);
  }

  if(!fs.existsSync(src)){
    console.error(`${file} not exist`);
    process.exit(4);
  }

  if(fs.statSync(src).isDirectory()){
    deleteDir(src);
  }

  if(fs.statSync(src).isFile()){
    fs.unlinkSync(src);
    console.log(`${file}删除成功!`)
  }
}

  function deleteDir(folder){
    let files = fs.readdirSync(folder);

    for(let i=0; i<files.length; i++){

      let f = join(folder,files[i]);

      if(fs.statSync(f).isFile()){
        fs.unlinkSync(f);
        continue;
      }

      if(fs.statSync(f).isDirectory()){
        deleteDir(f);
      }
    }

    fs.rmdirSync(folder);
    console.log(`${file}文件夹删除成功`);
    process.exit(5)
  }

